package revontuli.aMHD.datamanagement;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import revontuli.aMHD.dataclasses.Departure;
import revontuli.aMHD.dataclasses.Stop;
import revontuli.aMHD.dataclasses.Line;

public class XMLParser {
	/**
	 * Tato metoda pripravi objekt XMLReader, ktorym rozparsujeme xml data.
	 * @return Objekt, ktorym rozparsujeme xml vstupy.
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 */
	private XMLReader initialiseReader() throws SAXException, ParserConfigurationException {
		SAXParserFactory mSAXParserFactory = SAXParserFactory.newInstance();
		SAXParser mSAXParser = mSAXParserFactory.newSAXParser();
		XMLReader mXMLReader = mSAXParser.getXMLReader();
		return mXMLReader;
	}
	
	/**
	 * Metoda, ktora zabezpecuje vytvorenie struktury zastavok z xml vstupu.
	 * @param xml
	 * @return
	 */
	public ArrayList<Stop> parseStopList(String xml) {
		try {
			XMLReader mXMLReader = initialiseReader();
			StopXMLHandler mStopHandler = new StopXMLHandler();
			
			mXMLReader.setContentHandler(mStopHandler);
			mXMLReader.parse(new InputSource(new StringReader(xml)));
			
			return mStopHandler.retrieveStopList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Metoda, ktora zabezpecuje vytvorenie struktury liniek z xml vstupu.
	 * @param xml
	 * @return
	 */
	public ArrayList<Line> parseLineList(String xml) {
		try {
			XMLReader mXMLReader = initialiseReader();
			LineXMLHandler mLineHandler = new LineXMLHandler();
			
			mXMLReader.setContentHandler(mLineHandler);
			mXMLReader.parse(new InputSource(new StringReader(xml)));
			
			return mLineHandler.retrieveLineList();
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public ArrayList<Departure> parseDepartureList(String xml) {
		try {
			XMLReader mXMLReader = initialiseReader();
			DepartureXMLHandler mDepartureHandler = new DepartureXMLHandler();
			
			mXMLReader.setContentHandler(mDepartureHandler);
			mXMLReader.parse(new InputSource(new StringReader(xml)));
			
			return mDepartureHandler.retrieveDepartureList();
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
}
